/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package binaryfilter;

/**
 *
 * @author kinder
 */

import java.net.InetAddress;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import java.io.*;


public class BinaryFilter {

    public static void main(String[] args) {
      
         String path = args[0];
         String filename = args[1];
         String command = args[2];

        try {
         //Solr cell can also index MS file (2003 version and 2007 version) types.
         System.out.println(path);
         //this will be unique Id used by Solr to index the file contents.
         InetAddress ip = InetAddress.getByName("127.0.0.1");
         String hostname = ip.getHostName();
         String solrId = hostname + "|" + path;

         if(command.equals("INSERT"))
         {
            indexFilesSolrCell(path, filename, solrId);
         }
         else if(command.equals("UPDATE"))
         {

         }
         else if(command.equals("DELETE"))
         {
             deleteFilesSolrCell(solrId);
         }

       } catch (Exception ex) {
         //System.out.println(ex.toString());
           try
     {


          String homePath = System.getenv("HOME");
          String pathFileLog = homePath + "/.mediawhere/errors.log";
          FileOutputStream fos = new FileOutputStream(pathFileLog, true);
          PrintStream ps = new PrintStream(fos);
          Calendar cal = new GregorianCalendar();
          int giorno = cal.get(Calendar.DAY_OF_MONTH);
          int mese = cal.get(Calendar.MONTH);
          int anno = cal.get(Calendar.YEAR);
          //System.out.println(giorno + "/" + (mese + 1) + "/" + anno);
          String orario;
          int ore = cal.get(Calendar.HOUR);
          int minuti = cal.get(Calendar.MINUTE);
          int secondi = cal.get(Calendar.SECOND);

          if(cal.get(Calendar.AM_PM) == 0)
          orario = "A.M.";
          else
          orario = "P.M.";
          //System.out.println("Sono le : " + ore + ":"   + minuti + ":" + secondi + " " + orario);



          ps.println("ERROR. [" + giorno + "/" + (mese+1) + "/" + anno + "]  ["+ ore + ":"   + minuti + ":" + secondi + " " + orario +"]  Indexing file [" + path + "] failed:  " );
          ex.printStackTrace(ps);
          ps.println("\n\n");

      }
      catch (IOException e)
      {
          System.out.println("Errore: " + e);
          System.exit(1);
      }
       }
     }

     /*
      * Method to index all types of files into Solr.
      * @param fileName
      * @param solrId
      * @throws IOException
      * @throws SolrServerException
      */

     public static void indexFilesSolrCell(String pathName, String fileName, String solrId) throws IOException, SolrServerException {

       String urlString = "http://localhost:8983/solr";
       SolrServer solr = new CommonsHttpSolrServer(urlString);


       ContentStreamUpdateRequest up
         = new ContentStreamUpdateRequest("/update/extract");

       up.addFile(new File(pathName));

       up.setParam("literal.id", solrId);
       up.setParam("literal.filename", fileName);
       up.setParam("uprefix", "attr_");
       //up.setParam("fmap.content", "attr_content");

       //Sets appropriate parameters for the given ACTION
       //setAction(AbstractUpdateRequest.ACTION action,boolean waitFlush, boolean waitSearcher)
       up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);

       solr.request(up);

       QueryResponse rsp = solr.query(new SolrQuery(fileName));

       System.out.println(rsp);
     }

     public static void deleteFilesSolrCell(String solrId)
    {
        String home = System.getenv("HOME");
        System.out.println(home);
        File wd = new File(home + "/.mediawhere/found/");
        System.out.println(wd);
        Process proc = null;
        try {
           proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
        }
        catch (IOException e) {
           e.printStackTrace();
           return;
        }
        if (proc != null) {
           BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
           PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
           //out.println("cd /home/kinder/apache-solr-1.4.1/example/exampledocs/");
           out.println("java -Ddata=args -Dcommit=yes -jar post.jar " + "\"<delete><id>" + solrId + "</id></delete>\"");
           out.println("exit");
           //out.println("java -jar post.jar");
           try {
              String line;
              while ((line = in.readLine()) != null) {
                 System.out.println(line);
              }
              proc.waitFor();
              in.close();
              out.close();
              proc.destroy();
           }
           catch (Exception e) {
              e.printStackTrace();
           }
        }
    }
}

     